<template>
  <el-dialog
    :model-value="modelValue"
    @update:model-value="updateVisible"
    :close-on-click-modal="false"
    :title="button"
  >
    <el-form
      :model="dataForm"
      @keyup.enter="dataFormSubmit()"
      label-width="80px"
    >
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="dataForm.roleName" placeholder="角色名称" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="dataForm.remark" placeholder="备注" />
      </el-form-item>
      <el-form-item size="small" label="授权">
        <el-tree
          ref="treeRef"
          :data="menuList"
          :props="menuListTreeProps"
          node-key="menuId"
          :default-expand-all="false"
          :default-expanded-keys="expandedKeys"
          show-checkbox
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit()">
          {{ button }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { nextTick, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { reqMenuList, reqRoleInfo, reqRoleUpdateCommit } from '@/api/acl'
import { treeDataTranslate } from '@/utils/token.ts'

const dataForm = ref({
  id: 0,
  roleName: '',
  remark: '',
  menuIdList: [],
})
const button = ref('添加')
const menuList = ref([])
const treeRef = ref()
const tempKey = ref(-666666)
const expandedKeys = ref([])
const menuListTreeProps = ref({
  label: 'name',
  children: 'children',
})

defineProps(['modelValue'])

const emit = defineEmits(['update:modelValue'])

const updateVisible = (value: boolean) => {
  emit('update:modelValue', value)
}

// 处理取消按钮点击
const handleCancel = () => {
  updateVisible(false)
}

const dataFormSubmit = async () => {
  try {
    const response = await reqRoleUpdateCommit(
      dataForm.value.id > 0 ? 'update' : 'save',
      dataForm.value.id,
      dataForm.value.roleName,
      dataForm.value.remark,
      [
        ...treeRef.value.getCheckedKeys(),
        tempKey.value,
        ...treeRef.value.getHalfCheckedKeys(),
      ],
    )
    if (response.code === 0) {
      ElMessage.success(`角色${button.value}成功`)
    } else {
      ElMessage.error(response.msg)
    }
  } catch (error) {
    console.error(`角色${button.value}失败`, error)
  }
}

const init = (id: number) => {
  button.value = id > 0 ? '修改' : '添加'
  menuSelect()
  nextTick(async () => {
    dataForm.value.id = 0
    dataForm.value.roleName = ''
    dataForm.value.remark = ''
    expandedKeys.value = []
    treeRef.value.setCheckedKeys([])
    if (id > 0) {
      const response = await reqRoleInfo(id)
      if (response.code === 0) {
        const { roleName, remark, menuIdList } = response.role
        dataForm.value = {
          id,
          roleName,
          remark,
          menuIdList,
        }
        const idx = menuIdList.indexOf(-666666)
        if (idx !== -1) {
          menuIdList.splice(idx, menuIdList.length - idx)
        }
        treeRef.value?.setCheckedKeys(menuIdList)
        expandedKeys.value = menuIdList
      } else {
        ElMessage.error(response.msg)
      }
    }
  })
}

const menuSelect = async () => {
  const response = await reqMenuList()
  if (response) {
    menuList.value = treeDataTranslate(response, 'menuId')
  } else {
    ElMessage.error('角色添加页面-系统列表获取失败')
  }
}

// 暴露方法
defineExpose({ init })
</script>

<style scoped lang="scss"></style>
